package com.zjitc.token;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jdk.nashorn.internal.parser.TokenStream;
import org.junit.Test;
import sun.invoke.empty.Empty;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/2 14:22
 * @description:
 */
public class Cache {
  private Map<String,Token> tokens=new HashMap<>();

  public void add(String username,String uuid){
    tokens.put(username,new Token(uuid, LocalDateTime.now()));
  }

  public Token get(String username){
    return tokens.get(username);
  }

  public Set<Entry<String,Token>> getAllTokens(){
    return tokens.entrySet();
  }
/**
 *如何使用多线程，有后台一直对Cache进行扫描*/

  public static void main(String[] args) {
    Cache cache=new Cache();

    cache.add("a","a");
    cache.add("b","b");
    cache.add("c","c");

    ExecutorService executorService= Executors.newSingleThreadExecutor();
    Thread thread=new Thread();
    executorService.submit(()->{
      while (true){
        try {
          Thread.sleep(500);
        }catch (InterruptedException e){
          e.printStackTrace();
        }
        System.out.println(LocalDateTime.now());

        // 检查在ache中C,是否有数据过期，如果有，则将其打印出来
        Set<Entry<String,Token>> sets=cache.getAllTokens();

        //需要计算时间间隔
        for (Entry<String,Token>entry:sets){
          String key=entry.getKey();
          Token token=entry.getValue();

          LocalDateTime createTime=token.getCreateTime();
          LocalDateTime nowTime=LocalDateTime.now();


          //如何计算时间间隔
          Duration between=Duration.between(createTime,nowTime);
          if (between.abs().toMillis()>5000){
            System.out.println(token.getUuid());
          }
        }

      }
    });

    //td.start();

    Scanner scanner = new Scanner(System.in);
    scanner.next();

  }
    @Test
        public void during(){
      LocalDateTime t1=LocalDateTime.now();
      try {
        Thread.sleep(1000);
      }catch(InterruptedException e){
        e.printStackTrace();
      }

      LocalDateTime t2=LocalDateTime.now();
      System.out.println(t1);
      System.out.println(t2);

      Duration between=Duration.between(t1,t2);
      System.out.println(between.abs().getSeconds());

  }
}
